<template>
  <div id="app">
    <router-view />
    <!-- backtotop部分 -->
    <el-backtop :bottom="80" :right="40" />
  </div>
</template>
<script>
// import BackToTop from '@/components/BackToTop'
import * as common from '@/common/common'
export default {
  components: {
    // BackToTop
  },
  data() {
    return {
      timecheck: ''
    }
  },
  computed: {
    key() {
      return this.$route.path
    },
    isLogin() {
      return this.$store.getters.isLogin
    }
  },
  watch: {
    'isLogin': function(newVal, oldVal) {
      // 登陆状态，开始定时器，定时查看该账户是否有效
      // eslint-disable-next-line eqeqeq
      if (newVal == true) {
        clearInterval(this.timecheck)
        this.timecheck = ''
        this.timecheck = setInterval(() => {
          this.checkEnabled()
        }, 10000)
      } else {
        // 未登陆状态，清除定时器
        clearInterval(this.timecheck)
        this.timecheck = ''
      }
    }
  },
  // 进行一些系统初始化判断
  created() {
    this.init()
  },
  // 清除用户相关数据
  destroyed() {

  },
  methods: {
    async init() {
      // 自动登陆判断，如果本地有token，
      if (common.isExist('token')) {
      // 不存在token，未登陆状态，正常浏览页面
        const token = common.getItemFromsStorage('token')
        if (token) {
          localStorage.removeItem('userInfo')
          await this.$store.dispatch('user/getUserInfo').then(res => {
          // 保存用户信息在本地
            common.setItemToStorage('userInfo', res.object)
            // 获取收货地址，获取订单，获取购物车信息
            this.$store.dispatch('cart/getCarts', res.object.id)
            this.$store.dispatch('address/getUserAddress', res.object.id)
            this.$store.dispatch('order/getUserOrderList', res.object.id)
          }).catch(() => {
            this.$store.commit('user/SET_ISLOGIN', false)
            if (this.$route.meta.needLogin) {
              this.$router.push('/welcome')
            }
            // this.$nitify.error({
            //   title: '失败',
            //   message: '获取用户信息失败'
            // })
          })
        }
      }
    },
    checkEnabled() {
      this.$store.dispatch('user/getUserInfo').then(res => {
        // eslint-disable-next-line eqeqeq
        if (res.object.enable == 0) {
          // 清除登陆状态，清除用户数据，取消定时器，重定向到首页
          this.$message.error('您的账号已被禁用，自动退出')
          common.userMessageInit()
          clearInterval(this.timecheck)
          this.timecheck = ''
          if (this.$router.fullPath !== '/welcome') {
            this.$router.push('welcome')
          }
        }
      })
    }
  }

}
</script>

<style >
html,
body {
  margin: 0;
  color: black;
  /* height: 100%; */
  background-color: #f4f2ee !important;
}
</style>
<style  lang="scss" scoped>
.el-backtop {
  background-color: #ebeef5;
  box-shadow: 0 0 6px rgba(0, 0, 0, 0.12);
  text-align: center;
  line-height: 40px;
  color: #1989fa;
  border-radius: 5px;
}
</style>
